package cn.shop.merchant.service;

import cn.shop.merchant.util.IpUtil;
import cn.shop.transcation.detail.entity.FundDetail;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.transcation.rechargerecord.entity.Record;
import cn.shop.utils.enums.TransactionState;
import cn.shop.utils.exception.ServiceException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author : 李一涵
 * @date : Created in 2022/6/2 13:55
 * @description :
 */
@Service
public class ApiService {

    @Resource
    private MerchantUserService userService;
    @Resource
    private RechargeRecordService recordService;
    @Resource
    private FundDetailService fundDetailService;

    @Transactional(rollbackFor = Exception.class)
    public boolean recharge(MerchantUser user, BigDecimal amount, String channel) {
        boolean success = userService.lambdaUpdate().set(MerchantUser::getBalance, user.getBalance().add(amount))
                .eq(MerchantUser::getId, user.getId())
                .update();
        if (success) {
            Record record = new Record();
            record.setType(1);
            record.setActualAmount(amount);
            record.setChannelId(0L);
            record.setBalance(user.getBalance().add(amount));
            record.setChannel(channel);
            record.setIp(IpUtil.getClientIp());
            record.setPlayerId(user.getId());
            record.setPlayerName(user.getAccount());
            record.setAmount(amount);
            record.setState(TransactionState.COMPLETED);
            success = recordService.save(record);
            if (!success) {
                throw new ServiceException("充值失败");
            }
            FundDetail fundDetail = new FundDetail();
            fundDetail.setPlayerAccount(record.getPlayerName());
            fundDetail.setGoods("商户充值");
            fundDetail.setAmount(record.getActualAmount());
            fundDetail.setOrderId(record.getId());
            fundDetail.setIp(record.getIp());
            fundDetail.setPlayerId(record.getPlayerId());
            fundDetail.setBalance(record.getBalance());
            fundDetail.setDealTime(LocalDateTime.now());
            fundDetail.setPaySolution(channel);
            fundDetail.setChannelShare(record.getAmount().subtract(record.getActualAmount()));
            fundDetail.setAlias("www");
            fundDetail.setType(2);
            success = fundDetailService.save(fundDetail);
            if (!success) {
                throw new ServiceException("充值失败");
            }
            return true;
        } else {
            return false;
        }
    }

}
